from django.shortcuts import render
from django.views import View
from django import http
import json, re

from rest_framework import serializers

from apps.carts.utils import merge_cart_cookie_to_redis
from apps.goods.models import SKU
from apps.users.models import User, Address
from django.contrib.auth import login, authenticate, logout

from meiduo_mall.settings.dev import logger
from django_redis import get_redis_connection
from celery_tasks.email.tasks import send_email_verify_url

from meiduo_mall.utils.views import LoginRequiredJSONMixin
from apps.users.utils import generate_email_verify_url, check_email_verify_url


# Create your views here.
# 浏览记录
class UserBrowseHistory(LoginRequiredJSONMixin, View):
    def post(self, request):
        # 1.接收参数
        json_dict = json.loads(request.body.decode())
        sku_id = json_dict.get('sku_id')

        # 2.校验参数
        try:
            SKU.objects.get(pk=sku_id)
        except Exception as e:
            logger.error(e)
            return http.JsonResponse({'code': 400, 'errmsg': 'sku不存在'})

        # 3.redis--pipeline--lrem --lpush --ltrim --execute
        # list user.id:[1, 2 ,3]
        client = get_redis_connection('history')
        save_key = 'history_%s' % request.user.id
        p1 = client.pipeline()
        # 去重
        p1.lrem(save_key, 0, sku_id)
        # 插入
        p1.lpush(save_key, sku_id)
        # 切片
        p1.ltrim(save_key, 0, 4)
        p1.execute()

        # 4.返回响应对象
        return http.JsonResponse({'code': 0, 'errmsg': '记录成功!'})

    def get(self, request):
        # 2.1 获取用户id  request.user.id
        save_key = "history_%s" % request.user.id
        # 2.2 链接redis     lrange(k , 0,-1)
        client = get_redis_connection('history')
        sku_ids = client.lrange(save_key, 0, -1)

        # 2.3 遍历 sku_ids --->SKU 找 sku 对象
        skus_list = []
        for sku_id in sku_ids:
            sku = SKU.objects.get(pk=sku_id)
            skus_list.append({
                'id': sku.id,
                'name': sku.name,
                'default_image_url': sku.default_image.url,
                'price': sku.price
            })

        # 下面 这段代码  从获取skus的角度是没有任何问题 ; 但是顺序不对
        # skus = SKU.objects.filter(pk__in=sku_ids)
        # for sku in skus:
        #     skus_list.append({
        #         'id': sku.id,
        #         'name': sku.name,
        #         'default_image_url': sku.default_image.url,
        #         'price': sku.price
        #     })

        # 2.4 json([{}])
        return http.JsonResponse({'code': 0, 'errmsg': 'ok', 'skus': skus_list})


# 修改密码
class ChangePasswordView(LoginRequiredJSONMixin, View):
    """修改密码"""

    def put(self, request):
        """实现修改密码逻辑"""
        # 接收参数
        dict = json.loads(request.body.decode())
        old_password = dict.get('old_password')
        new_password = dict.get('new_password')
        new_password2 = dict.get('new_password2')

        # 校验参数
        if not all([old_password, new_password, new_password2]):
            return http.JsonResponse({'code': 400,
                                      'errmsg': '缺少必传参数'})

        result = request.user.check_password(old_password)
        if not result:
            return http.JsonResponse({'code': 400,
                                      'errmsg': '原始密码不正确'})

        if not re.match(r'^[0-9A-Za-z]{8,20}$', new_password):
            return http.JsonResponse({'code': 400,
                                      'errmsg': '密码最少8位,最长20位'})

        if new_password != new_password2:
            return http.JsonResponse({'code': 400,
                                      'errmsg': '两次输入密码不一致'})

        # 修改密码
        try:
            request.user.set_password(new_password)
            request.user.save()
        except Exception as e:
            logger.error(e)
            return http.JsonResponse({'code': 400,
                                      'errmsg': '修改密码失败'})

        # 清理状态保持信息
        logout(request)

        response = http.JsonResponse({'code': 0,
                                      'errmsg': 'ok'})

        response.delete_cookie('username')

        # # 响应密码修改结果：重定向到登录界面
        return response


# 设置地址标题
class UpdateTitleAddressView(LoginRequiredJSONMixin, View):
    """设置地址标题"""

    def put(self, request, address_id):
        """设置地址标题"""
        # 接收参数：地址标题
        json_dict = json.loads(request.body.decode())
        title = json_dict.get('title')

        try:
            # 查询地址
            address = Address.objects.get(id=address_id)

            # 设置新的地址标题
            address.title = title
            address.save()
        except Exception as e:
            logger.error(e)
            return http.JsonResponse({'code': 400, 'errmsg': '设置地址标题失败'})

        # 4.响应删除地址结果
        return http.JsonResponse({'code': 0, 'errmsg': '设置地址标题成功'})


# 设置默认地址
class DefaultAddressView(LoginRequiredJSONMixin, View):
    """设置默认地址"""

    def put(self, request, address_id):
        """设置默认地址"""
        try:
            # 接收参数,查询地址
            address = Address.objects.get(id=address_id)

            # 设置地址为默认地址
            request.user.default_address = address
            request.user.save()
        except Exception as e:
            logger.error(e)
            return http.JsonResponse({'code': 400,
                                      'errmsg': '设置默认地址失败'})

        # 响应设置默认地址结果
        return http.JsonResponse({'code': 0,
                                  'errmsg': '设置默认地址成功'})


# 修改,删除地址
class UpdateDestroyAddressView(LoginRequiredJSONMixin, View):
    """修改和删除地址"""

    def put(self, request, address_id):
        """修改地址"""
        # 接收参数
        json_dict = json.loads(request.body.decode())
        receiver = json_dict.get('receiver')
        province_id = json_dict.get('province_id')
        city_id = json_dict.get('city_id')
        district_id = json_dict.get('district_id')
        place = json_dict.get('place')
        mobile = json_dict.get('mobile')
        tel = json_dict.get('tel')
        email = json_dict.get('email')

        # 校验参数
        if not all([receiver, province_id, city_id, district_id, place, mobile]):
            return http.JsonResponse({'code': 400, 'errmsg': '缺少必传参数'})

        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return http.JsonResponse({'code': 400, 'errmsg': '参数mobile有误'})

        if tel:
            if not re.match(r'^(0[0-9]{2,3}-)?([2-9][0-9]{6,7})+(-[0-9]{1,4})?$', tel):
                return http.JsonResponse({'code': 400, 'errmsg': '参数tel有误'})
        if email:
            if not re.match(r'^[a-z0-9][\w\.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$', email):
                return http.JsonResponse({'code': 400, 'errmsg': '参数email有误'})

        # 判断地址是否存在,并更新地址信息
        try:
            Address.objects.filter(id=address_id).update(
                user=request.user,
                title=receiver,
                receiver=receiver,
                province_id=province_id,
                city_id=city_id,
                district_id=district_id,
                place=place,
                mobile=mobile,
                tel=tel,
                email=email
            )
        except Exception as e:
            logger.error(e)
            return http.JsonResponse({'code': 400, 'errmsg': '更新地址失败'})

        # 构造响应数据
        address = Address.objects.get(id=address_id)
        address_dict = {
            "id": address.id,
            "title": address.title,
            "receiver": address.receiver,
            "province": address.province.name,
            "city": address.city.name,
            "district": address.district.name,
            "place": address.place,
            "mobile": address.mobile,
            "tel": address.tel,
            "email": address.email
        }

        # 响应更新地址结果
        return http.JsonResponse({'code': 0, 'errmsg': '更新地址成功', 'address': address_dict})

    def delete(self, request, address_id):
        """删除地址"""
        try:
            # 查询要删除的地址
            address = Address.objects.get(id=address_id)

            # 将地址逻辑删除设置为True
            address.is_deleted = True
            address.save()
        except Exception as e:
            logger.error(e)
            return http.JsonResponse({'code': 400, 'errmsg': '删除地址失败'})

        # 响应删除地址结果
        return http.JsonResponse({'code': 0, 'errmsg': '删除地址成功'})


# 展示地址
class AddressView(LoginRequiredJSONMixin, View):
    """用户收货地址"""

    def get(self, request):
        """提供地址管理界面
        """
        # 获取所有的地址:
        addresses = Address.objects.filter(user=request.user, is_deleted=False)

        # 创建空的列表
        address_dict_list = []
        # 遍历
        for address in addresses:
            address_dict = {
                "id": address.id,
                "title": address.title,
                "receiver": address.receiver,
                "province": address.province.name,
                "city": address.city.name,
                "district": address.district.name,
                "place": address.place,
                "mobile": address.mobile,
                "tel": address.tel,
                "email": address.email
            }

            # 将默认地址移动到最前面
            default_address = request.user.default_address
            if default_address.id == address.id:
                # 查询集 addresses 没有 insert 方法
                address_dict_list.insert(0, address_dict)
            else:
                address_dict_list.append(address_dict)

        default_id = request.user.default_address_id

        return http.JsonResponse({'code': 0,
                                  'errmsg': 'ok',
                                  'addresses': address_dict_list,
                                  'default_address_id': default_id})


# 新增地址
class CreateAddressView(LoginRequiredJSONMixin, View):
    """新增地址"""

    def post(self, request):
        """实现新增地址逻辑"""
        # 获取地址个数:
        count = Address.objects.filter(user=request.user, is_deleted=False).count()

        # 判断是否超过地址上限：最多20个
        if count >= 20:
            return http.JsonResponse({'code': 400, 'errmsg': '超过地址数量上限'})

        # 1. 接收参数
        json_dict = json.loads(request.body.decode())
        receiver = json_dict.get('receiver')
        province_id = json_dict.get('province_id')
        city_id = json_dict.get('city_id')
        district_id = json_dict.get('district_id')
        place = json_dict.get('place')
        mobile = json_dict.get('mobile')
        tel = json_dict.get('tel')
        email = json_dict.get('email')

        # 2. 校验参数
        if not all([receiver, province_id, city_id, district_id, place, mobile]):
            return http.JsonResponse({'code': 400,
                                      'errmsg': '缺少必传参数'})

        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return http.JsonResponse({'code': 400, 'errmsg': '参数mobile有误'})

        if tel:
            if not re.match(r'^(0[0-9]{2,3}-)?([2-9][0-9]{6,7})+(-[0-9]{1,4})?$', tel):
                return http.JsonResponse({'code': 400, 'errmsg': '参数tel有误'})
        if email:
            if not re.match(r'^[a-z0-9][\w\.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$', email):
                return http.JsonResponse({'code': 400, 'errmsg': '参数email有误'})

        # 保存地址信息
        try:
            address = Address.objects.create(
                user=request.user,
                title=receiver,
                receiver=receiver,
                province_id=province_id,
                city_id=city_id,
                district_id=district_id,
                place=place,
                mobile=mobile,
                tel=tel,
                email=email
            )
            # 设置默认地址
            if not request.user.default_address:
                request.user.default_address = address
                request.user.save()
        except Exception as e:
            logger.error(e)
            return http.JsonResponse({'code': 400, 'errmsg': '新增地址失败'})

        # 新增地址成功，将新增的地址响应给前端实现局部刷新
        address_dict = {
            "id": address.id,
            "title": address.title,
            "receiver": address.receiver,
            "province": address.province.name,
            "city": address.city.name,
            "district": address.district.name,
            "place": address.place,
            "mobile": address.mobile,
            "tel": address.tel,
            "email": address.email
        }

        # 响应保存结果
        return http.JsonResponse({'code': 0, 'errmsg': '新增地址成功', 'address': address_dict})


# 验证激活邮箱
class EmailActiveView(View):
    """验证激活邮箱
    PUT /emails/verification/
    """

    def put(self, request):
        """实现验证激活邮箱的逻辑"""
        # 接收参数
        token = request.GET.get('token')

        # 校验参数
        if not token:
            return http.JsonResponse({'code': 400, 'errmsg': '缺少token'})

        # 实现核心逻辑
        # 通过token提取要验证邮箱的用户
        user = check_email_verify_url(token=token)

        # 将要验证邮箱的用户的email_active字段设置True
        try:
            user.email_active = True
            user.save()
        except Exception as e:
            logger.error(e)
            return http.JsonResponse({'code': 400, 'errmsg': '邮箱验证失败'})

        # 响应结果
        return http.JsonResponse({'code': 0, 'errmsg': '邮箱验证成功'})


# 添加邮箱
class EmailView(LoginRequiredJSONMixin, View):
    """添加邮箱"""

    def put(self, request):
        """实现添加邮箱的逻辑"""
        # 接收参数
        json_dict = json.loads(request.body.decode())
        email = json_dict.get('email')

        # 校验参数
        if not email:
            return http.JsonResponse({'code': 400, 'errmsg': '缺少必传参数'})
        # 校验邮箱格式
        if not re.match(r'^[a-z0-9][\w\.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$', email):
            return http.JsonResponse({'code': 400, 'errmsg': '参数email格式错误'})

        # 实现核心逻辑：添加邮箱就是将用户填写的邮箱地址保存到当前登录用户的email字段即可
        try:
            request.user.email = email
            request.user.save()
        except Exception as e:
            logger.error(e)
            return http.JsonResponse({'code': 400, 'errmsg': '添加邮箱失败'})

        # 发送邮箱的验证激活邮件：耗时操作，不能让他阻塞主逻辑，需要从主逻辑中解耦出来，celery
        # verify_url = '测试的激活链接'
        verify_url = generate_email_verify_url(user=request.user)
        send_email_verify_url.delay(email, verify_url)

        # 响应结果
        return http.JsonResponse({'code': 0, 'errmsg': 'OK'})


# 用户中心
class UserInfoView(LoginRequiredJSONMixin, View):
    """用户中心"""

    def get(self, request):
        data_dict = {
            'code': 0,
            'errmsg': 'OK',
            'info_data': {
                'username': request.user.username,
                'mobile': request.user.mobile,
                'email': request.user.email,
                'email_active': request.user.email_active
            }
        }
        return http.JsonResponse(data_dict)


# class UserInfoView(LoginrequiresJSONMixin, View):
#     """用户中心"""
#     def get(self, request):
#         return http.JsonResponse({
#             'code': 0,
#             'errmsg': '个人中心',
#             "info_data": {
#                 "username": "zs",
#                 "mobile": "15144556677",
#                 "email": "",
#                 "email_active": 'true'
#             }
#         })


class LogoutView(View):
    """用户退出"""

    def delete(self, request):
        # 清楚session
        logout(request)
        # 清楚cookie--username
        response = http.JsonResponse({'code': '0', 'errmsg': '退出登录成功'})
        response.delete_cookie('username')
        # 返回
        return response


class LoginView(View):
    def post(self, request):
        """用户登录"""
        # 接收、提取参数
        json_dict = json.loads(request.body.decode())
        account = json_dict.get('username')
        password = json_dict.get('password')
        remembered = json_dict.get('remembered')

        # 校验参数
        if not all([account, password]):
            return http.JsonResponse({'code': 400, 'errmsg': '缺少必传参数'})

        if not re.match(r'^[0-9A-Za-z]{8,20}$', password):
            return http.JsonResponse({'code': 400, 'errmsg': '参数password格式错误'})

        # 实现多账号登录
        if re.match(r'^1[3-9]\d{9}$', account):
            User.USERNAME_FIELD = 'mobile'
        else:
            User.USERNAME_FIELD = 'username'

        # 认证登录用户
        # 与数据库进行判断，看用户名和密码是否一致，authenticate判断登录 密码加密对比
        user = authenticate(request=request, username=account, password=password)
        if not user:
            return http.JsonResponse({'code': 400, 'errmsg': '用户名或密码错误'})

        # 保持登录状态
        login(request, user)
        # 是否记住登录，本质是session什么时候过期
        if remembered:
            # 记住登录，2周过期
            request.session.set_expiry(None)
        else:
            # 不记住，登录就过期
            request.session.set_expiry(0)

        # 在登录成功后，将用户名写入到cookie，将来会在页面右上角展示
        response = http.JsonResponse({'code': 0, 'errmsg': '注册成功'})
        # 合并购物车
        merge_cart_cookie_to_redis(request, response)
        response.set_cookie('username', user.username, max_age=14 * 24 * 3600)

        # 响应结果
        return response


class RegisterView(View):
    """用户注册
    POST http://www.meiduo.site:8000/register/
    """

    def post(self, request):
        """实现注册逻辑"""
        # 接收参数:请求体中的JSON数据
        json_bytes = request.body
        json_str = json_bytes.decode()
        json_dict = json.loads(json_str)
        # json_dict = json.loads(request.body.decode())

        # 提取参数
        username = json_dict.get('username')
        password = json_dict.get('password')
        password2 = json_dict.get('password2')
        mobile = json_dict.get('mobile')
        # 提取短信验证码
        sms_code_clinet = json_dict.get('sms_code')
        allow = json_dict.get('allow')

        # 校验参数
        # 判断是否缺少必传参数
        if not all([username, password, password2, mobile, sms_code_clinet, allow]):
            return http.JsonResponse({'code': '400', 'errmsg': '缺少必传的参数'})

        # 判断用户名是否满足项目格式要求
        if not re.match(r'^[a-zA-Z0-9_-]{5,20}$', username):
            return http.JsonResponse({'code': '400', 'errmsg': '参数username有误'})

        # 判断password
        if not re.match(r'^[a-zA-Z0-9]{8,20}$', password):
            return http.JsonResponse({'code': '400', 'errmsg': '参数password有误'})

        # 判断password2 和 password
        if password != password2:
            return http.JsonResponse({'code': 400, 'errmsg': '两次输入不对'})

        # 6.mobile检验
        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return http.JsonResponse({'code': 400, 'errmsg': 'mobile格式有误'})

        # 判断短信验证码是否正确
        # 提取服务端存储的短信验证码
        redis_conn = get_redis_connection('verify_code')
        sms_code_server = redis_conn.get('sms_%s' % mobile)

        if not sms_code_server:
            return http.JsonResponse({'code': 400, 'errmsg': '短信验证码失效'})
        if sms_code_clinet != sms_code_server.decode():
            return http.JsonResponse({'code': 400, 'errmsg': 'mobile格式有误'})

        # 7.allow检验
        if allow != True:
            return http.JsonResponse({'code': 400, 'errmsg': 'allow格式有误'})

        # 实现核心逻辑:保存注册数据到用户数据表
        try:
            user = User.objects.create_user(username=username, password=password, mobile=mobile)
        except Exception as e:
            logger.error(e)
            return http.JsonResponse({'code': 400, 'errmsg': '注册失败'})

        # 实现状态保持
        login(request, user)

        # 在注册成功后，将用户名写入到cookie，将来会在页面右上角展示
        response = http.JsonResponse({'code': 0, 'errmsg': '注册成功'})
        response.set_cookie('username', user.username, max_age=14 * 24 * 3600)

        # 响应结果
        return response


class UserInfoSerializer(serializers.ModelSerializer):
    def get(self, request):
        id = serializers.IntegerField()
        username = serializers.CharField()
        mobile = serializers.CharField()
        email = serializers.CharField()
        email_active = serializers.CharField()


class UserInfoModelSerializer(serializers.ModelSerializer):

    class Meta:
        model = User
        fields={'username', 'mobile', 'email', 'email_active'}


class UserModelSerializer(serializers.ModelSerializer):
    password2 = serializers.CharField(write_only=True)
    sms_code = serializers.CharField(write_only=True)
    allow = serializers.BooleanField(write_only=True)

    class Meta:
        model = User
        fields = ['username', 'password', 'mobile', 'sms_code', 'allow']
        extra_kwargs = {
            'username': {
                'max_length': 20,
                'min_length': 5
            },
            'password': {
                'write_only': True
            }
        }
    def validate(self, attrs):
        mobile = attrs.get('mobile')
        sms_code_clinet = attrs.get('sms_code')
        redis_conn = get_redis_connection('verify_code')
        sms_code_server = redis_conn.get('sms_%s' % mobile)
        if not sms_code_server:
            raise serializers.ValidationError('验证码过期')
        if sms_code_clinet != sms_code_server.decode():
            raise serializers.ValidationError('验证码不一样')
        return attrs



class UserCountView(View):
    """用户名是否重复注册
    GET http://www.meiduo.site:8000/usernames/itcast/count/
    """

    def get(self, request, username):
        try:
            # 查询用户名对应的记录个数
            count = User.objects.filter(username=username).count()
        except Exception as e:
            logger.error(e)
            return http.JsonResponse({'code': 400, 'errmsg': '访问数据库失败'})
        # 返回结果
        return http.JsonResponse({'code': '0', 'errmsg': 'OK', 'count': count})


class MobileCountView(View):
    """手机号是否重复注册
    GET http://www.meiduo.site:8000/mobiles/18646794341/count/
    """

    def get(self, request, mobile):
        try:
            # 查询手机号对应的记录
            count = User.objects.filter(mobile=mobile).count()
        except Exception as e:
            return http.JsonResponse({'code': 400, 'errmsg': '访问数据库失败'})
        # 返回结果
        return http.JsonResponse({'code': 0, 'errmsg': 'OK', 'count': count})
